﻿Imports DevExpress.LookAndFeel
Imports System.Security.Cryptography
Imports System.Text

Public Class Login
    Public Function base64Decode(ByVal sData As String) As String
        Dim encoder As New System.Text.UTF8Encoding()
        Dim utf8Decode As System.Text.Decoder = encoder.GetDecoder()
        Dim todecode_byte As Byte() = Convert.FromBase64String(sData)
        Dim charCount As Integer = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length)
        Dim decoded_char As Char() = New Char(charCount - 1) {}
        utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0)
        Dim result As String = New [String](decoded_char)
        Return result
    End Function
    Private Function GetMD5HashData(ByVal data As String) As String
        Dim md5 As MD5 = md5.Create
        Dim hashData As Byte() = md5.ComputeHash(Encoding.[Default].GetBytes(data))
        Dim returnValue As New StringBuilder()
        Dim i As Integer = 0
        While (i < hashData.Length)
            returnValue.Append(hashData(i).ToString())
            System.Math.Max(System.Threading.Interlocked.Increment(i), i - 1)
        End While
        Return returnValue.ToString()
    End Function
    Public Function Decode(ByVal Data As String, ByVal Depth As Integer) As String
        Dim TempChar As String
        Dim TempAsc As Integer
        Dim NewData As String = ""
        Dim vChar As Integer

        For vChar = 1 To Len(Data)
            TempChar = Mid$(Data, vChar, 1)
            TempAsc = Asc(TempChar)
            If Depth = 0 Then Depth = 40
            If Depth > 254 Then Depth = 254
            TempAsc = TempAsc - Depth
            If TempAsc < 0 Then TempAsc = TempAsc + 255
            TempChar = Chr(TempAsc)
            NewData = NewData & TempChar
        Next vChar

        Decode = NewData
    End Function
    Public Function MD5Encrypt(ByVal str As String) As String
        Dim md5 As MD5CryptoServiceProvider
        Dim bytValue() As Byte
        Dim bytHash() As Byte
        Dim strOutput As String = ""
        Dim i As Integer

        ' Create New Crypto Service Provider Object
        md5 = New MD5CryptoServiceProvider

        ' Convert the original string to array of Bytes
        bytValue = System.Text.Encoding.UTF8.GetBytes(str)

        ' Compute the Hash, returns an array of Bytes
        bytHash = md5.ComputeHash(bytValue)
        md5.Clear()

        For i = 0 To bytHash.Length - 1
            'don't lose the leading 0
            strOutput &= bytHash(i).ToString("x").PadLeft(2, "0")
        Next

        MD5Encrypt = strOutput
    End Function
    Private Function ValidateMD5HashData(ByVal inputData As String, ByVal storedHashData As String) As Boolean
        'hash input text and save it string variable
        Dim getHashInputData As String = GetMD5HashData(inputData)

        If String.Compare(getHashInputData, storedHashData) = 0 Then
            Return True
        Else
            Return False
        End If
    End Function
    Public Function Decrypt(ByVal toDecrypt As String, ByVal key As String, ByVal useHashing As Boolean) As String
        Dim keyArray As Byte()
        Dim toEncryptArray As Byte()
        Try
            toEncryptArray = Convert.FromBase64String(toDecrypt.Replace(" ", "+"))
        Catch ex As Exception
            toEncryptArray = Convert.FromBase64String(toDecrypt)
        End Try

        If useHashing = True Then
            Dim hashmd5 As New MD5CryptoServiceProvider()
            keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key))
        Else
            keyArray = UTF8Encoding.UTF8.GetBytes(key)
        End If
        Dim tdes As New TripleDESCryptoServiceProvider()
        tdes.Key = keyArray
        tdes.Mode = CipherMode.ECB
        tdes.Padding = PaddingMode.PKCS7
        Dim cTransform As ICryptoTransform = tdes.CreateDecryptor()
        Dim resultArray As Byte() = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length)
        Return UTF8Encoding.UTF8.GetString(resultArray)
    End Function
    Private Sub SimpleButton1_Click(sender As System.Object, e As System.EventArgs) Handles SimpleButton1.Click
        Me.Dispose()
        Main.Close()
        Application.ExitThread()
    End Sub
    Private Sub SimpleButton2_Click(sender As System.Object, e As System.EventArgs) Handles SimpleButton2.Click
        DangNhap()
    End Sub
    Function GetDatabaseName(ByVal connString As String) As String
        Dim lcConnString = connString.ToLower()

        ' if this is a Jet database, find the index of the "data source" setting
        Dim startIndex As Integer
        If lcConnString.IndexOf("jet.oledb") > -1 Then
            startIndex = lcConnString.IndexOf("data source=")
            If startIndex > -1 Then startIndex += 12
        Else
            ' if this is a SQL Server database, find the index of the "initial 
            ' catalog" or "database" setting
            startIndex = lcConnString.IndexOf("initial catalog=")
            If startIndex > -1 Then
                startIndex += 16
            Else ' if the "Initial Catalog" setting is not found,
                '  try with "Database"
                startIndex = lcConnString.IndexOf("database=")
                If startIndex > -1 Then startIndex += 9
            End If
        End If

        ' if the "database", "data source" or "initial catalog" values are not 
        ' found, return an empty string
        If startIndex = -1 Then Return ""

        ' find where the database name/path ends
        Dim endIndex As Integer = lcConnString.IndexOf(";", startIndex)
        If endIndex = -1 Then endIndex = lcConnString.Length

        ' return the substring with the database name/path
        Return connString.Substring(startIndex, endIndex - startIndex)
    End Function
    Private Function GetIPv4Address() As String
        GetIPv4Address = String.Empty
        Dim strHostName As String = System.Net.Dns.GetHostName()
        Dim iphe As System.Net.IPHostEntry = System.Net.Dns.GetHostEntry(strHostName)
        For Each ipheal As System.Net.IPAddress In iphe.AddressList
            If ipheal.AddressFamily = System.Net.Sockets.AddressFamily.InterNetwork Then
                GetIPv4Address = ipheal.ToString()
            End If
        Next
    End Function
    Public Sub DangNhap()
        If Me.TaiKhoanHeThongTableAdapter.getCheckAccount(Me.MaITextEdit.EditValue.ToString.Trim) = 1 Then

            If Me.base64Decode(Me.TaiKhoanHeThongTableAdapter.getPassword(Me.MaITextEdit.EditValue.ToString.Trim)) = Me.MatkhauITextEdit.EditValue Then
                Me.Hide()
                Main.BarStaticItemUser.Caption = Me.MaITextEdit.EditValue
                Main.BarStaticItemTime.Caption = Today
                Main.BarStaticItemIpaddress.Caption = GetIPv4Address()
                Main.BarStaticItemDataBase.Caption = GetDatabaseName(My.MySettings.Default.PCV_CLINICConnectionString)
                Main.Show()
            Else
                DevExpress.XtraEditors.XtraMessageBox.Show("Mật khẩu không đúng !!!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error)
                Me.MatkhauITextEdit.Focus()
            End If
        End If
    End Sub
    Public Sub New()
        InitializeComponent()
        DevExpress.Skins.SkinManager.EnableFormSkins()
        DevExpress.UserSkins.BonusSkins.Register()
        UserLookAndFeel.Default.SetSkinStyle("Office 2010 Blue")
    End Sub

    Private Sub NhomatkhauCheckBox_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles NhomatkhauCheckBox.KeyDown
        If e.KeyCode = Keys.Enter Then
            Me.SimpleButton2.Focus()
        End If
    End Sub

    Private Sub Login_Load(sender As Object, e As EventArgs) Handles Me.Load
      
    End Sub
End Class